package com.accloud.cloudservice;

import com.accloud.service.ACException;
import com.accloud.utils.AesUtil;
import com.accloud.utils.Crc16Util;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import org.java_websocket.drafts.Draft_75;

/* access modifiers changed from: package-private */
public class HttpSecuritySession {
    private final String aesKey;

    public HttpSecuritySession(String aesKey2) {
        this.aesKey = aesKey2;
    }

    public byte[] encrypt(LocalMessage message) throws GeneralSecurityException {
        byte[] content = message.payload;
        byte[] bytes = ByteBuffer.allocate(content.length + 4).put((byte) 1).put((byte) message.msgCode).putShort((short) Crc16Util.GetCrc16(content, content.length)).put(content).array();
        return this.aesKey != null ? AesUtil.encrypt(bytes, this.aesKey.getBytes()) : bytes;
    }

    public LocalMessage decrypt(byte[] encrypted) throws GeneralSecurityException, ACException {
        byte[] bytes;
        if (this.aesKey != null) {
            bytes = AesUtil.decrypt(encrypted, this.aesKey.getBytes());
        } else {
            bytes = encrypted;
        }
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.get();
        byte msgCode = buffer.get();
        int crc = buffer.getShort() & 65535;
        int length = bytes.length - 4;
        byte[] payload = ByteBuffer.allocate(length).put(bytes, 4, length).array();
        if (Crc16Util.GetCrc16(payload, payload.length) == crc) {
            return new LocalMessage(msgCode & Draft_75.END_OF_FRAME, payload);
        }
        throw new ACException(ACException.INTERNAL_ERROR, "Local message fail CRC check");
    }
}
